#include "mainwindow.h"
#include <QPushButton>
#include <QLabel>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QStyle>
#include <QApplication>
#include <QGraphicsDropShadowEffect>
#include <QDesktopWidget>
#include <QMouseEvent>
#include <QTimer>
#include <QDateTime>
#include "im.h"
#include "mm.h"
#include "sm.h"

MainWindow::MainWindow(const QMap<QString, QVariant> &userInfo, QWidget *parent): QWidget(parent),
      m_bDragging(false),
      m_titleBar(nullptr),
      m_stackedWidget(nullptr),
      m_statusBar(nullptr),
      m_contentWidget(nullptr),
      m_maximizeRestoreButton(nullptr),
      m_timeLabel(nullptr),
      m_imanage(nullptr),
      m_mmanage(nullptr),
      m_smanage(nullptr),
      m_currentUser(userInfo)
{
    // 设置窗口为无边框且支持最大化/最小化按钮
    setWindowFlags(Qt::FramelessWindowHint | Qt::WindowMinMaxButtonsHint);
    // 设置透明背景以实现圆角效果
    setAttribute(Qt::WA_TranslucentBackground);
    // 设置窗口最小尺寸
    setMinimumSize(800, 600);
    setObjectName("mainWindow");
    initUI();

    // 先显示窗口,然后最大化
    show();
    showMaximized();

    // 设置最大化状态下的UI
    layout()->setContentsMargins(0, 0, 0, 0);
    m_contentWidget->setGraphicsEffect(nullptr);
    m_maximizeRestoreButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_TitleBarNormalButton));
}

MainWindow::~MainWindow()
{
}

void MainWindow::initUI()
{
    // 主布局管理器，设置边距和间距
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(10, 10, 10, 10);
    mainLayout->setSpacing(0);

    // 创建内容容器，用于承载所有UI组件
    m_contentWidget = new QWidget(this);
    m_contentWidget->setObjectName("contentWidget");
    m_contentWidget->setStyleSheet("#contentWidget { background: white; border-radius: 5px; }");

    // 内容布局管理器
    QVBoxLayout *contentLayout = new QVBoxLayout(m_contentWidget);
    contentLayout->setContentsMargins(0, 0, 0, 0);
    contentLayout->setSpacing(0);

    // 创建自定义标题栏
    m_titleBar = new QWidget(m_contentWidget);
    m_titleBar->setObjectName("titleBar");
    m_titleBar->setFixedHeight(30);

    // 标题栏图标
    QLabel *iconLabel = new QLabel(m_titleBar);
    iconLabel->setPixmap(QApplication::style()->standardIcon(QStyle::SP_ComputerIcon).pixmap(16, 16));

    // 标题文本
    QLabel *titleLabel = new QLabel("超市收银系统", m_titleBar);
    titleLabel->setAlignment(Qt::AlignCenter);

    // 窗口控制按钮
    QPushButton *minimizeButton = new QPushButton(m_titleBar);
    minimizeButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_TitleBarMinButton));
    minimizeButton->setFlat(true);

    // 最大化/还原按钮
    m_maximizeRestoreButton = new QPushButton(m_titleBar);
    m_maximizeRestoreButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_TitleBarMaxButton));
    m_maximizeRestoreButton->setFlat(true);

    // 关闭按钮
    QPushButton *closeButton = new QPushButton(m_titleBar);
    closeButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_TitleBarCloseButton));
    closeButton->setFlat(true);

    // 标题栏布局
    QHBoxLayout *titleLayout = new QHBoxLayout(m_titleBar);
    titleLayout->setContentsMargins(5, 0, 5, 0);
    titleLayout->setSpacing(5);
    titleLayout->addWidget(iconLabel);
    titleLayout->addWidget(titleLabel, 1);
    titleLayout->addWidget(minimizeButton);
    titleLayout->addWidget(m_maximizeRestoreButton);
    titleLayout->addWidget(closeButton);

    // 创建堆叠窗口用于页面切换
    m_stackedWidget = new QStackedWidget(m_contentWidget);

    // 创建导航栏
    QWidget *navBar = new QWidget(m_contentWidget);
    navBar->setObjectName("navBar");
    navBar->setFixedHeight(40);

    // 导航栏布局
    QHBoxLayout *navLayout = new QHBoxLayout(navBar);
    navLayout->setContentsMargins(10, 0, 10, 0);
    navLayout->setSpacing(5);

    // 创建导航按钮
    QStringList navItems = {"进销存管理", "会员管理", "系统管理", "帮助"};
    QList<QPushButton*> navButtons;
    for (int i = 0; i < navItems.size(); i++) {
        QPushButton *navButton = new QPushButton(navItems[i], navBar);
        navButton->setObjectName("navButton");
        navButton->setCheckable(true);
        navButtons.append(navButton);

        // 默认选中第一个按钮
        if (i == 0) {
            navButton->setChecked(true);
            navButton->setStyleSheet("background-color: rgba(255, 255, 255, 0.3); font-weight: bold;");
        }

        // 连接按钮点击信号，切换页面并更新按钮状态
        connect(navButton, &QPushButton::clicked, [this, i, navButtons]() {
            m_stackedWidget->setCurrentIndex(i);
            for (int j = 0; j < navButtons.size(); j++) {
                if (j == i) {
                    navButtons[j]->setStyleSheet("background-color: rgba(255, 255, 255, 0.3); font-weight: bold;");
                } else {
                    navButtons[j]->setStyleSheet("");
                }
            }
        });

        navLayout->addWidget(navButton);
    }

    // 关键：添加伸缩项，将时间标签推到导航栏最右侧
    navLayout->addStretch();

    // 创建时间显示标签（导航栏最右侧）
    m_timeLabel = new QLabel(navBar);
    m_timeLabel->setObjectName("timeLabel");
    m_timeLabel->setStyleSheet("color: white; padding: 0 10px; font-size: 12px;"); // 白色文字+内边距，适配导航栏高度
    navLayout->addWidget(m_timeLabel);

    // 创建各功能页面
    m_imanage = new im(m_currentUser, this);
    m_mmanage = new mm(this);
    m_smanage = new sm(this);

    // 帮助页面
    QWidget *helpPage = new QWidget();
    QVBoxLayout *helpLayout = new QVBoxLayout(helpPage);
    helpLayout->setContentsMargins(10, 10, 10, 10);
    QLabel *helpLabel = new QLabel("帮助页面 - 这里显示帮助相关内容", helpPage);
    helpLabel->setAlignment(Qt::AlignCenter);
    helpLayout->addWidget(helpLabel);
    helpPage->setStyleSheet("background-color: #CCCCFF;");

    // 添加页面到堆叠窗口
    m_stackedWidget->addWidget(m_imanage);
    m_stackedWidget->addWidget(m_mmanage);
    m_stackedWidget->addWidget(m_smanage);
    m_stackedWidget->addWidget(helpPage);
    m_stackedWidget->setCurrentIndex(0);

    // 将导航栏、堆叠窗口、状态栏添加到内容布局
    contentLayout->addWidget(navBar);
    contentLayout->addWidget(m_stackedWidget, 1); // 伸缩因子1，占满剩余空间
    m_statusBar = new QStatusBar(m_contentWidget);
    m_statusBar->setSizeGripEnabled(false);
    m_statusBar->setStyleSheet("background: #f0f0f0; border-top: 1px solid #d0d0d0;");
    contentLayout->addWidget(m_statusBar);

    // 将标题栏插入到内容布局顶部
    contentLayout->insertWidget(0, m_titleBar);

    // 为内容窗口添加阴影效果（非最大化时显示）
    QGraphicsDropShadowEffect *shadowEffect = new QGraphicsDropShadowEffect(m_contentWidget);
    shadowEffect->setBlurRadius(10);
    shadowEffect->setColor(QColor(0, 0, 0, 150));
    shadowEffect->setOffset(0, 0);
    m_contentWidget->setGraphicsEffect(shadowEffect);

    // 将内容窗口添加到主布局
    mainLayout->addWidget(m_contentWidget);

    // 连接窗口控制按钮信号槽
    connect(minimizeButton, &QPushButton::clicked, this, &MainWindow::onMinimizeButtonClicked);
    connect(m_maximizeRestoreButton, &QPushButton::clicked, this, &MainWindow::onMaximizeRestoreButtonClicked);
    connect(closeButton, &QPushButton::clicked, this, &MainWindow::onCloseButtonClicked);

    // 设置应用程序样式表
    setStyleSheet(
        "#mainWindow { background: transparent; }"
        "#titleBar { "
        "   background-color: #07C160; "
        "   border-top-left-radius: 5px; "
        "   border-top-right-radius: 5px; "
        "}"
        "#navBar { "
        "   background-color: #4CAF50; "
        "}"
        "#navButton { "
        "   background-color: transparent; "
        "   color: white; "
        "   border: none; "
        "   padding: 5px 15px; "
        "   border-radius: 3px; "
        "}"
        "#navButton:hover { "
        "   background-color: rgba(255, 255, 255, 0.2); "
        "}"
        "QLabel { "
        "   color: white; "
        "   font-weight: bold; "
        "}"
        "QPushButton { "
        "   color: white; "
        "   background: transparent; "
        "   border: none; "
        "   padding: 2px; "
        "}"
        "QPushButton:hover { "
        "   background-color: #505050; "
        "   border-radius: 2px; "
        "}"
        "QPushButton:pressed { "
        "   background-color: #787878; "
        "}"
    );

    // 启用鼠标跟踪（窗口拖拽需要）
    setMouseTracking(true);
    m_contentWidget->setMouseTracking(true);

    // 初始化时间显示 + 启动定时器（每秒更新一次，确保秒数实时变化）
    updateTimeDisplay();
    QTimer *timeTimer = new QTimer(this);
    timeTimer->setInterval(1000); // 1秒 = 1000毫秒
    connect(timeTimer, &QTimer::timeout, this, &MainWindow::updateTimeDisplay);
    timeTimer->start();
}

// 核心函数：更新时间显示（格式：2025年09月03日星期三 当前时间：21:37:29）
void MainWindow::updateTimeDisplay()
{
    if (!m_timeLabel) return; // 防止空指针崩溃

    QDateTime currentTime = QDateTime::currentDateTime();

    // 1. 格式化公历日期+星期（Qt 5.12兼容，直接用toString格式化星期）
    // "yyyy年MM月dd日" → 2025年09月03日；"dddd" → 星期三（依赖系统locale，中文环境下自动显示中文星期）
    QString dateWeekStr = currentTime.toString("yyyy年MM月dd日dddd");

    // 2. 格式化实时时间（HH=24小时制，mm=分钟，ss=秒）
    QString hourMinSecStr = currentTime.toString("HH:mm:ss");

    // 3. 拼接最终显示文本
    QString finalTimeStr = QString("%1 当前时间：%2").arg(dateWeekStr).arg(hourMinSecStr);

    // 设置到标签显示
    m_timeLabel->setText(finalTimeStr);
}

// 鼠标按下事件处理：检测标题栏拖拽
void MainWindow::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        if (m_titleBar && m_titleBar->geometry().contains(event->pos())) {
            // 如果是最大化状态，先恢复为正常大小
            if (isMaximized()) {
                showNormal();
                layout()->setContentsMargins(10, 10, 10, 10);

                // 恢复窗口阴影效果
                QGraphicsDropShadowEffect *shadowEffect = new QGraphicsDropShadowEffect();
                shadowEffect->setBlurRadius(10);
                shadowEffect->setColor(QColor(0, 0, 0, 150));
                shadowEffect->setOffset(0, 0);
                m_contentWidget->setGraphicsEffect(shadowEffect);

                // 更新按钮图标为最大化图标
                m_maximizeRestoreButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_TitleBarMaxButton));

                // 设置窗口大小为800×600
                resize(800, 600);

                // 计算窗口移动位置（让鼠标位于标题栏中间）
                QPoint mouseGlobalPos = event->globalPos();
                int titleBarHeight = m_titleBar->height();
                QPoint newWindowPos(
                    mouseGlobalPos.x() - width() / 2,
                    mouseGlobalPos.y() - titleBarHeight / 2
                );

                // 确保窗口不超出屏幕
                QRect screenGeometry = QApplication::desktop()->availableGeometry(this);
                newWindowPos.setX(qMax(screenGeometry.left(), qMin(newWindowPos.x(), screenGeometry.right() - width())));
                newWindowPos.setY(qMax(screenGeometry.top(), qMin(newWindowPos.y(), screenGeometry.bottom() - height())));

                move(newWindowPos);
            }

            // 标记拖拽状态
            m_bDragging = true;
            m_StartPos = event->globalPos();
            m_WindowPos = this->pos();
            event->accept();
            return;
        }
    }
    QWidget::mousePressEvent(event);
}

// 鼠标移动事件处理：实现窗口拖拽
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    if (m_bDragging) {
        QPoint delta = event->globalPos() - m_StartPos;
        move(m_WindowPos + delta);
        event->accept();
    } else {
        QWidget::mouseMoveEvent(event);
    }
}

// 鼠标释放事件处理：结束拖拽状态
void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton && m_bDragging) {
        m_bDragging = false;
        event->accept();
    } else {
        QWidget::mouseReleaseEvent(event);
    }
}

// 鼠标双击事件处理：标题栏双击最大化/还原
void MainWindow::mouseDoubleClickEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton && m_titleBar && m_titleBar->geometry().contains(event->pos())) {
        onMaximizeRestoreButtonClicked();
        event->accept();
    } else {
        QWidget::mouseDoubleClickEvent(event);
    }
}

// 最小化窗口
void MainWindow::onMinimizeButtonClicked()
{
    showMinimized();
}

// 最大化/还原窗口切换
void MainWindow::onMaximizeRestoreButtonClicked()
{
    if (isMaximized()) {
        showNormal();
        layout()->setContentsMargins(10, 10, 10, 10);

        // 恢复窗口阴影效果
        QGraphicsDropShadowEffect *shadowEffect = new QGraphicsDropShadowEffect();
        shadowEffect->setBlurRadius(10);
        shadowEffect->setColor(QColor(0, 0, 0, 150));
        shadowEffect->setOffset(0, 0);
        m_contentWidget->setGraphicsEffect(shadowEffect);

        // 更新按钮图标为最大化图标
        m_maximizeRestoreButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_TitleBarMaxButton));
    } else {
        // 移除边距和阴影效果，使窗口填满屏幕
        layout()->setContentsMargins(0, 0, 0, 0);
        m_contentWidget->setGraphicsEffect(nullptr);
        showMaximized();
        // 更新按钮图标为还原图标
        m_maximizeRestoreButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_TitleBarNormalButton));
    }
}

// 关闭窗口
void MainWindow::onCloseButtonClicked()
{
    close();
}

QMap<QString, QVariant> MainWindow::getCurrentUser() const
{
    return m_currentUser;
}
